<%@ Control Language="C#" ClassName="Notes" Inherits="Dimok.Web.UI.TableControl" %>
<%@ Register TagPrefix="UI" src="~/Controls/_UI/Note/Children/NoteWarnings.ascx" TagName="NoteWarnings" %>
<%@ Import Namespace="System.Data" %>
<script runat="server">
	int ApplID_Prev = 0;
	bool dataBindDsNotes = false;
	Dimok.Aspx.Manager.UOX uox { get { return new Dimok.Aspx.Manager.UOX(); } }
	public int ApplID {
		get {
			try {
				if (!dataBindDsNotes) dataBindDsNotes = fv.RequiresDataBinding = true;
				int o = (int)Lib.GetProperty(Page, "LoanID");
				dsNote.EmtyRowPolicy = o > 0 ? Dimok.Data.DataSources.EmptyRowPolicyType.OnlyIfEmpty : Dimok.Data.DataSources.EmptyRowPolicyType.None;
				return o;
			} catch (Exception exc) {
				throw new Exception("Applicant ID error.", exc);
			}
		}
	}
	string GetCollectBy() {
	 return Data.SQL.ExecuteScalar("SELECT LOWER(dbo.Collection_CollectBy(@ApplID))", ApplID) + ""; 
	}
	string GetNotePhone() { return Data.SQL.ExecuteScalar("SELECT dbo.FormatPhone(dbo.Collection_NotePhoneLast(@ApplID))", ApplID) + ""; }
	protected override void OnInit(EventArgs e) {
		base.OnInit(e);
		dsNote.Selecting += new ObjectDataSourceSelectingEventHandler(dsNote_Selecting);
		dsNote.Selected += new ObjectDataSourceStatusEventHandler(dsNote_Selected);
		grv.AllowEdit = true;// new Dimok.Aspx.Manager.UOX().IsAdmin;
		grv.ShowDelete = uox.IsAdmin;
		new FormView().ItemCreated += new EventHandler(Notes_ItemCreated);
		grv.SelectedIndexChanged += new EventHandler(grv_SelectedIndexChanged);
	}

	protected override void OnLoad(EventArgs e) {
		base.OnLoad(e);
		//if( !IsPostBack )
		//  ScriptManager.RegisterOnSubmitStatement(this, GetType(),"URL Encode", Dimok.FileManager.GetTextFromFile(Context.Server.MapPath("~/Controls/_UI/Note/Notes.js")));
		grv.HideColumns = "statususer,statusdate,isresolved,loanID";
		JS.ScriptLocalID(this, pnlNote);
	}

	void Note_Reset(object sender) {
		ITextControl txtNote = ((Control)sender).FindControl("txtNote") as ITextControl;
		if (txtNote != null) txtNote.Text = "";
		Note = "";
	}
	void grv_SelectedIndexChanged(object sender, EventArgs e) {
		Note_Reset(sender);
	}

	protected void ShowNoteStatus(object sender, EventArgs e) {
		ListControl lc = sender as ListControl;
		lc.Visible = lc.Items.Count > 1;
		Dimok.Web.UI.Find.ChildByType(lc.Parent, typeof(Label)).Visible = lc.Items.Count <= 1;
	}

	void ShowNextButton(object sender, EventArgs e) {
		//((Control)sender).Visible = (bool)Data.SQL.ExecuteScalar("SELECT dbo.Collection_ShowNextButton(@LoanID)", ApplID);
	}

	protected void ResolveCollection(object sender, EventArgs e) {
		if( Data.SQL.ExecuteSP("s_Collection_Resolve", ApplID) == 0 )
			throw new Exception("Must add a Collection Note in order to go to Next Account.");
	}

	void dsNote_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {
		dsNote.EmtyRowPolicy = ApplID > 0 ? Dimok.Data.DataSources.EmptyRowPolicyType.OnlyIfEmpty : Dimok.Data.DataSources.EmptyRowPolicyType.None;
		//dsNote.SelectList += ",ISNULL(DateDueBy,dbo.Collection_CollectBy(" + ApplID + "))CollectBy";
	}

	void Notes_ItemCreated(object sender, EventArgs e) {
		//if (ApplID_Prev == ApplID) return;
		Note_Reset(sender);
	}
	bool WasSentToNatasha(int applID) {
		bool wasSent = Cache[applID + ""] != null;
		Cache[applID + ""] = true;
		return wasSent;
	}
	void SendEMailToNatasha(int ApplID) {
		if (WasSentToNatasha(ApplID)) return;
		string from = uox.Mail+"";
		if( from == "" )from = "HELP@AFCHOME.NET";
		new System.Net.Mail.SmtpClient("AFCMAIL").Send(from, "NATASHA@AFCHOME.NET", "USIX Import:" + ApplID, "http://motobankcorp.afchome.net/manager/USIX/USIXBridge.aspx?ApplID=" + ApplID);
	}
	bool NoteUpdated = false;
	void fv_ItemUpdating(object sender, FormViewUpdateEventArgs e) {
		if (ApplID > 0 && ApplID < 1000000) {
			SendEMailToNatasha(ApplID);
			throw new Exception("This account must be imported from USIX.\nCall HATASHA @ 2059.");
		}
		if (e.Keys[0] == DBNull.Value)
			e.NewValues["LoanID"] = ApplID;
		if ((e.NewValues["NoteTypeID"] + "") == "")
			e.NewValues["NoteTypeID"] = ((DropDownList)fv.FindControl("selNoteType")).SelectedValue;
		if (Lib.MakeInt(e.NewValues["NoteTypeID"]) == 0) throw new Exception("Must select Note Type.");
		if (Lib.MakeInt(e.NewValues["NoteActionCodeID"]) == 0) throw new Exception("Must select Note Action Code.");
		//e.NewValues["Note"] = Context.Server.UrlDecode(e.NewValues["Note"] + "");
		Note_Reset(sender);
		NoteUpdated = true;
	}

	void DateDue_Binding(object sender, EventArgs e) {
		ITextControl tc = (ITextControl)sender;
		if (tc.Text == "") tc.Text = new Dimok.Aspx.Manager.Lib.WS().FetchNoteDateDue(0);
		ScriptLocal(sender, e);
	}
	void ScriptLocal(object sender, EventArgs e) {
		Dimok.Web.UI.JS.ScriptLocalID(Page, sender as Control);
	}
	void Ext_PreRender(object sender, EventArgs e) {
		((HtmlInputText)sender).Value= new Profiler(Page).profile.IPPhone.Extention;
		ScriptLocal(sender, e);
	}
	void Pwd_PreRender(object sender, EventArgs e) {
		((HtmlInputPassword)sender).Value = new Profiler(Page).profile.IPPhone.Password;
		ScriptLocal(sender, e);
	}
	void XmlNotePhones_PreRender(object sender, EventArgs e) {
		((HtmlGenericControl)sender).InnerHtml = "";
		ScriptLocal(sender, e);
	}

	void CollectBy_Load(object sender, EventArgs e) {
		((TextBoxWatermarkExtender)sender).WatermarkText = Dimok.User.UserObject.CurrentUserName;
	}
	string GetNote(Control c) { return ((TextBox)c.Parent.FindControl("txtNote")).Text; }
	string GetNoteTypeID(Control c) { return ((DropDownList)c.Parent.FindControl("selNoteType")).Text; }
	string _NoteActionCodeID(Control c) { return ((DropDownList)c.Parent.FindControl("selActionCode")).Text; }
	void _NoteActionCodeID(Control c,int index) {
		ListControl lc =  c.Parent.FindControl("selActionCode")as ListControl;
		if (lc != null) lc.SelectedIndex = index;
	}
	string Note = "";
	protected void txtNote_TextChanged(object sender, EventArgs e) {
		Note = ((TextBox)sender).Text;
		NoteTypeID = GetNoteTypeID(sender as Control);
		NoteActionCodeID = _NoteActionCodeID(sender as Control);
	}
	string NoteTypeID = "0";
	protected void selNoteType_SelectedIndexChanged(object sender, EventArgs e) {
		NoteTypeID = ((DropDownList)sender).SelectedValue;
		NoteActionCodeID = "0";
	}
	string NoteActionCodeID = "0";
	protected void selActionCode_SelectedIndexChanged(object sender, EventArgs e) {
		NoteActionCodeID = ((DropDownList)sender).SelectedValue;
		NoteTypeID = GetNoteTypeID(sender as Control);
	}
	DataTable PhonesToDial = null;
	void dsNote_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
		if (ApplID >= 0 && ApplID < 1000000 && ((DataView)e.ReturnValue).Count > 0) {
			ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "NOTE_WARNING",
				"alert('You wil not be able to enter notes in this account.\\nCall Natasha @ 2059 to import this account from USIX.')", true);
			SendEMailToNatasha(ApplID);
		}
		DataView dv = e.ReturnValue as DataView;
		if (dv != null && dv.Count == 1 && dv[0]["ID"] == DBNull.Value) {
			dv[0]["NoteTypeID"] = NoteTypeID;
			if (!NoteUpdated) dv[0]["NoteActionCodeID"] = NoteActionCodeID;
			dv[0]["Note"] = Note;
			dv[0]["DateDueBy"] = GetCollectBy();
			//dv[0]["Phone"] = GetNotePhone();
			dv[0]["IsResolved"] = true;
		}
		//PhonesToDial = new Data.DataSources.Collection_PhonesToDialDataSource().SelectEx(ApplID).Table;
		//PhonesToDial.Rows.InsertAt(
	}

	protected override void SetStateValues(Hashtable values) {
		base.SetStateValues(values);
		Note = values["Notes.Note"] + "";
		NoteTypeID = values["Notes.NoteTypeID"] + "";
		NoteActionCodeID = values["Notes.NoteActionCodeID"] + "";
		ApplID_Prev = (int)values[ClientID + "ApplID_Prev"];
	}
	protected override void GetStateValues(Hashtable values) {
		base.GetStateValues(values);
		values["Notes.Note"] = Note;
		values["Notes.NoteTypeID"] = NoteTypeID;
		values["Notes.NoteActionCodeID"] = NoteActionCodeID;
		values[ClientID + "ApplID_Prev"] = ApplID;
	}
	[System.Web.Services.WebMethod]
	public static string FetchNoteResultCodes(int noteActionCodeID) {
		try {
			DataTable dt = ((DataView)new NoteActionCode_StatusesDataSource(noteActionCodeID).Select()).Table;
			return dt.DataSet.GetXml();
		} catch (Exception exc) { throw new Dimok.Exceptions.ClientException(exc); }
	}
	protected void UpdateNoteStatus(object sender, EventArgs e) {
		Data.SQL.Note.UpdateStatus(sender);
	}
</script>
<style>
TABLE.w100 {width:100%}
.noOver {overflow:hidden}
.waterMark{color:LightGrey;font-weight:bold}
.NoteHover{}
.NotePopup{white-space:pre;background-color:BlanchedAlmond;border:solid 1px silver}
</style>
<UI:NoteWarnings id="Warnings" runat="server" AllowPaging="false" />
<table>
<tr><td>
		<fieldset style="border-color:#5377A9;display:inline">
		<legend state="+"><label style="color:#4A6A96;font-weight:bold;font-size:140%">Add/View Note</label></legend>
		<div>
<asp:UpdatePanel ID="upNote" UpdateMode="Always" EnableViewState="false" runat="server">
	<ContentTemplate>
		<UI:FormViewEx DataSourceID="dsNote" OnItemCreated="Notes_ItemCreated" OnItemUpdating="fv_ItemUpdating" DataKeyNames="ID" ID="fv" DefaultMode="Edit" EnableViewState="false" runat="server" style="width:100%">
		<EditItemTemplate>
		<div NoWrap="NoWrap" style="display:inline;font-family:Arial">
			<b>Note Type:</b> 
				<asp:DropDownList SelectedValue='<%#Bind("NoteTypeID")%>' ID="selNoteType" OnSelectedIndexChanged="selNoteType_SelectedIndexChanged" DataSourceID="dsNT" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true" AutoPostBack="false" runat="server"
						 onchange="fetchNoteActionCodes(selActionCode(),this.value||0)" style="vertical-align:middle"
				>
				<asp:ListItem Text="Select ..." Value="0" />
			</asp:DropDownList>
			<DS:Note_Type_ActionCodesDataSource ID="dsN_T_ACs" OrderBys="IsTask,ActionCode" runat="server">
				<SelectParameters><asp:ControlParameter ControlID="selNoteType" Name="TypeID" PropertyName="SelectedValue" Type="Int32" />
				</SelectParameters>
			</DS:Note_Type_ActionCodesDataSource>

			<b>Action Code:</b> 
				<UI:DropDownListEx SelectedValue='<%#Bind("NoteActionCodeID")%>' OnSelectedIndexChanged="selActionCode_SelectedIndexChanged" OnPreRender="ScriptLocal" ID="selActionCode" DataSourceID="dsN_T_ACs" DataTextField="ActionLabel" DataValueField="ActionCodeID" AutoPostBack="false" AppendDataBoundItems="true" runat="server"
					onchange="fetchNoteResultCodes(selStatus,this.value||0);hdnNoteActionCodeID().value=this.value" style="vertical-align:middle"
				><asp:ListItem Text="" Value="0"></asp:ListItem>
			</UI:DropDownListEx>
			<asp:HiddenField ID="hdnNoteActionCodeID" Value='<%#Bind("NoteActionCodeID")%>' OnPreRender="ScriptLocal" runat="server" />
			<DS:StateFlowNextStatesDataSource ID="dsSN" StateFromID='<%#int.Parse("0"+Eval("StatusID"))%>' runat="server" />
			<DS:NoteActionCode_StatusesDataSource ID="dsStatesByAccess" EmtyRowPolicy="9" OrderBys='<%#Eval("ID")==DBNull.Value?"Status":""%>' runat="server">
				<SelectParameters>
					<asp:ControlParameter ControlID="hdnNoteActionCodeID" PropertyName="Value" Name="NoteActionCodeID" Type="Int32" />
				</SelectParameters>
			</DS:NoteActionCode_StatusesDataSource>

			<b>Result Code:</b> 
			<asp:HiddenField ID="hdnStateID" Value='<%#Bind("StatusID")%>' OnPreRender="ScriptLocal" runat="server" />
			<select ID="selStatus" onchange="fetchDateDue(this.value||0);hdnStateID().value=this.value" style="vertical-align:middle" >
				<asp:Repeater DataSourceID="dsStatesByAccess" runat="server">
					<ItemTemplate><option Value='<%#Eval("StatusID")%>'><%#Eval("Status")%></option></ItemTemplate>
				</asp:Repeater>
			</select>
			<asp:DropDownList Visible="false" SelectedValue='<%#Eval("StatusID")%>' ID="selStatusID" OnPreRender="ScriptLocal" runat="server"
					 DataSourceID='<%#Eval("ID")==DBNull.Value?"dsStatesByAccess":"dsSN"%>'
					 DataTextField='<%#Eval("ID")==DBNull.Value?"Status":"StateTo"%>'
					 DataValueField='<%#Eval("ID")==DBNull.Value?"StatusID":"StateToID"%>'
					 AppendDataBoundItems='<%#Eval("ID")==DBNull.Value%>'
					 onchange="fetchDateDue(this.value||0)" EnableViewState="false"
			><asp:ListItem Value="" Text="" />
			</asp:DropDownList>
			<b>Phone #:</b>
			<asp:TextBox ID="txtNotePhone" xmlSrc="xmlNotePhones"
					 text='<%#Bind("Phone") %>' OnPreRender="ScriptLocal" style="width:11ex;overflow-x:visible;vertical-align:middle" runat="server"></asp:TextBox>
			<xml id="xmlNotePhones" runat="server" onprerender="XmlNotePhones_PreRender"></xml>

			Ext:
			<input id="txtExt" size="3" style="overflow-x:visible;vertical-align:middle" onprerender="Ext_PreRender" runat="server" />
			Pwd:
			<input id="txtPwd" size="3" style="overflow-x:visible;vertical-align:middle" type="password" onprerender="Pwd_PreRender" runat="server"  />
			<input type="button" value="Dial" onclick="dial(txtExt().value,txtPwd().value,txtNotePhone().value)" style="vertical-align:middle" />
			</div>
			<asp:TextBox TextMode="MultiLine" OnPreRender="ScriptLocal" Text='<%#Bind("Note")%>' ID="txtNote" OnTextChanged="txtNote_TextChanged" runat="server" style="overflow:visible;white-space:pre;font-family:Monospace;display:block;width:400px;border:1 solid darkgray" />
			<br />

			<b>Next Coll. Date:</b> <asp:TextBox ID="txtDateDue" OnDataBinding="DateDue_Binding" onchange="this.changed=true;" Text='<%#Bind("DateDue","{0:d}")%>' Columns="10" style="overflow-x:visible" runat="server" />
			<ajaxtk:CalendarExtender TargetControlID="txtDateDue" runat="server"/>

			<b>Next Coll. By:</b> 
				<asp:DropDownList SelectedValue='<%#Bind("DateDueBy")%>' ID="dsDueDateBy"  DataSourceID="dsLoginsDataSource" DataTextField="DisplayName" DataValueField="sAMAccountNameLower" AutoPostBack="false" runat="server"  AppendDataBoundItems="true"
						 style="vertical-align:middle">
						 <asp:ListItem></asp:ListItem>
			</asp:DropDownList>
			<DS:LoginsDataSource ID="dsLoginsDataSource" runat="server" />
<%--			<asp:TextBox ID="txtDateDueBy" disabled runat="server" Text='<%#Bind("DateDueBy")%>' />
			<ajaxtk:TextBoxWatermarkExtender runat="server" TargetControlID="txtDateDueBy" OnLoad="CollectBy_Load" WatermarkCssClass="waterMark" />
--%>
			<b style="cursor:hand" onclick="alert('What?! Without speakers?')">Listen:</b>
			<DS:VoiceDataSource id="dsVoice" NoteID='<%#Eval("ID")==DBNull.Value?0:Eval("ID")%>' runat="server"></DS:VoiceDataSource>
			<asp:DropDownList ID="ddlVoice" DataSourceID="dsVoice" DataTextField="StatusDate" DataValueField="StatusDate" runat="server"></asp:DropDownList>
			<asp:Button Text='<%#Eval("ID") == DBNull.Value?"Add New Note":"Update Note"%>' CommandName="Update" runat="server" />
			<asp:CheckBox ID="chkIsResolved" Checked='<%#Bind("IsResolved")%>' runat="server" Text="Resolved" CssClass="CheckBox" />
			<asp:Button OnClick="ResolveCollection" runat="server" Text="Next" OnPreRender="ShowNextButton" />
		</EditItemTemplate>
		</UI:FormViewEx>
	</ContentTemplate>
</asp:UpdatePanel>
</div>
		</fieldset>
</td></tr>
<tr><td>
<ajaxtk:CollapsiblePanelExtender runat="server"
	TargetControlID="pnlCBT"
	CollapseControlID="pnlCBTHeader" ExpandControlID="pnlCBTHeader"
	TextLabelID="lblCBTLabel"
	ImageControlID="imgCBTPanel"
	CollapsedImage="~/images/Buttons/expand.jpg" ExpandedImage="~/images/Buttons/collapse.jpg"
	Collapsed="false"	CollapsedText="" ExpandedText=""
	SuppressPostBack="true"
	
></ajaxtk:CollapsiblePanelExtender>
<asp:Panel ID="pnlCBTHeader" CssClass="PanelHeaderBlue" style="width:100%" runat="server">
<table cellPadding="0" cellSpacing="0"><tr>
<th Width="1px"><asp:Image ID="imgCBTPanel" ImageUrl="~/images/Buttons/expand.jpg" runat="server" />
<td nowrap><label ID="lblCBTLabel" runat="server" style="text-align:center">Notes</label></td>
</tr></table>
</asp:Panel> 
<asp:Panel ID="pnlCBT" runat="server" CssClass="PannelContent">

<asp:UpdatePanel ID="upNotes" UpdateMode="Always" runat="server"><ContentTemplate>
		<UI:GridViewMB ID="grv" runat="server" AutoGenerateColumns="False" DataSourceID="ds" style="width:auto"
			AllowSorting="True"	DataKeyNames="ID" EnableViewState="false" ShowFooter="false" EmptyDataRowStyle-Font-Bold="true" EmptyDataText="No comments"
			RowStyle-VerticalAlign="Top" OnRowClick="void" RowStyle-CssClass="Notes"  AllowPaging="true"
			>
			<Columns>
	<asp:ImageField DataImageUrlField="NoteTypeIconURL" DataImageUrlFormatString="/images/{0}"  />
<asp:TemplateField HeaderText="Note" SortExpression="Note">
	<ItemStyle CssClass="noOver" />
	<ItemTemplate>
		<asp:Label onmouseover='InitNoteHover(this,this.parentElement.all.tags("PRE")[0].outerHTML)' Text='<%#Lib.Substring(Eval("Note"),30)%>' style='<%#(Eval("Note")+"").Length>30?"color:navy;cursor:hand":""%>' ID="lblNote" runat="server" />
		<span style="display:none"><pre><%#(Eval("Note")+"").Length>0?Lib.FormatNote(Eval("Note")+"",100):""%></pre></span>
		<%--<ajaxtk:HoverMenuExtender id="hvrNote" HoverCssClass="NoteHover" HoverDelay="300" OffsetX="50" TargetControlID="lblNote" PopupControlID="pnlNote" BehaviorID="hvrNote1" runat="server" />--%>
	</ItemTemplate>
	<EditItemTemplate><asp:TextBox TextMode="MultiLine" style="width:250pt;font-family:Monospace;white-space:normal" Text='<%# Bind("Note") %>' ID="txtNote" runat="server" /></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone" SortExpression="Phone">
	<ItemTemplate><span title="Click to dial" style="cursor:hand" onclick='dial("","",<%#"\""+Eval("Phone","{0}")+"\""%>);event.cancelBubble=true;'><%#Lib.FormatPhone(Eval("Phone"))%></span></ItemTemplate>
	<EditItemTemplate><asp:TextBox Text='<%# Bind("Phone") %>' ID="txtPhone" runat="server" /></EditItemTemplate>
	<FooterTemplate><asp:TextBox ID="Phone" runat="server" /></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type" SortExpression="NoteType">
	<ItemTemplate><asp:Label ToolTip='<%#Eval("NoteType")%>' Text='<%#Eval("NoteTypeNick")%>' runat="server"></asp:Label></ItemTemplate>
	<EditItemTemplate>
		<asp:DropDownList SelectedValue='<%#Bind("NoteTypeID")%>' ID="selNoteTypeID" DataSourceID="dsNT" DataTextField="Name" DataValueField="ID" runat="server"/>
	</EditItemTemplate>
	<FooterTemplate>
		<DS:NoteTypesDataSource ID="dsNT" runat="server" />
		<asp:DropDownList ID="NoteTypeID" DataSourceID="dsNT" DataTextField="Name" DataValueField="ID" runat="server"/>
	</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actn" SortExpression="NoteActionCode">
	<ItemTemplate><asp:Label ToolTip='<%#Eval("NoteActionCode")%>' Text='<%#Eval("NoteActionCodeNick")%>' runat="server"></asp:Label></ItemTemplate>
	<EditItemTemplate>
		<asp:DropDownList SelectedValue='<%#Bind("NoteActionCodeID")%>' ID="selNoteActionCodeID" DataSourceID="dsNAC" DataTextField="Name" DataValueField="ID" runat="server"/>
	</EditItemTemplate>
	<FooterTemplate>
		<DS:NoteActionCodesDataSource ID="dsNAC" runat="server" />
		<asp:DropDownList ID="NoteActionCodeID" DataSourceID="dsNAC" DataTextField="Name" DataValueField="ID" runat="server"/>
	</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Result" SortExpression="StatusNick">
	<ItemTemplate>
			<DS:StateFlowNextStatesDataSource ID="dsSN_Edit" StateFromID='<%#int.Parse("0"+Eval("StatusID"))%>' runat="server" />
		<asp:DropDownList SelectedValue='<%#Bind("StatusID")%>' OnDataBound="ShowNoteStatus" onclick="event.cancelBubble=true;" onchange="if(!confirm('Change status?'))return;" NoteID='<%#Eval("ID")%>' ID="selStatusID" DataSourceID="dsSN_Edit" DataTextField="StateTo" DataValueField="StateToID" AutoPostBack="true" OnSelectedIndexChanged="UpdateNoteStatus" runat="server"/>
		<asp:Label ToolTip='<%#Eval("Status")%>' Text='<%#Eval("StatusNick")%>' runat="server"></asp:Label>
	</ItemTemplate>
	<EditItemTemplate>
		<DS:StateFlowNextStatesDataSource ID="dsSN_Edit" StateFromID='<%#int.Parse("0"+Eval("StatusID"))%>' runat="server" />
		<asp:DropDownList SelectedValue='<%#Bind("StatusID")%>' ID="selStatusID" DataSourceID="dsSN_Edit" DataTextField="StateTo" DataValueField="StateToID" runat="server"/>
	</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Netx Coll." SortExpression="DateDue">
	<ItemTemplate><%#Eval("DateDue", "{0:MM/dd/yy HH:mm}")%></ItemTemplate>
	<EditItemTemplate><asp:TextBox Text='<%# Bind("DateDue") %>' ID="txtDateDue" runat="server" /></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Next Coll. By" SortExpression="DateDueBy">
	<ItemTemplate><%#Eval("DateDueBy")%></ItemTemplate>
	<EditItemTemplate><asp:TextBox Text='<%# Bind("DateDueBy") %>' ID="txtDateDueBy" runat="server" /></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="NoteDate">
	<ItemTemplate><%#Eval("NoteDate", "{0:MM/dd/yy HH:mm}")%></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NoteUser" SortExpression="NoteUser">
	<ItemTemplate><%#Eval("NoteUser") %></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="StatusUser" HeaderText="StatusUser" ItemStyle-BackColor="WhiteSmoke" SortExpression="StatusUser" />
<asp:BoundField DataField="StatusDate" HeaderText="StatusDate" DataFormatString="{0:MM/dd/yy HH:mm}" ItemStyle-BackColor="WhiteSmoke" SortExpression="StatusDate" />
<asp:BoundField DataField="IsResolved" HeaderText="Res" ItemStyle-BackColor="WhiteSmoke" SortExpression="IsResolved" />
<asp:BoundField DataField="LoanID" HeaderText="LoanID" ItemStyle-BackColor="WhiteSmoke" SortExpression="LoanID" />
			</Columns>
		</UI:GridViewMB>

		<DS:NotesDataSource ID="dsNote" 
			SelectList="[ID],[LoanID],[Note],[StatusID],[StatusDate],[StatusUser],[DateDue],[DateDueBy],[NoteTypeID],[NoteActionCodeID],[Phone],[PhoneCategoryID],IsResolved"
			InsertList="[ID],[LoanID],[Note],[StatusID],[StatusDate],[StatusUser],[DateDue],[DateDueBy],[NoteTypeID],[NoteActionCodeID],[Phone],[PhoneCategoryID],IsResolved"
			UpdateList="[ID],[LoanID],[Note],[StatusID],[StatusDate],[StatusUser],[DateDue],[DateDueBy],[NoteTypeID],[NoteActionCodeID],[Phone],[PhoneCategoryID],IsResolved"
			 EmtyRowPolicy="None" runat="server">
			<SelectParameters><asp:ControlParameter ControlID="grv" PropertyName="SelectedValue" Name="ID" DefaultValue="0" /></SelectParameters>
		</DS:NotesDataSource>
		<DS:NoteActionCodesDataSource ID="dsNAC" runat="server" />
		<DS:NoteTypesDataSource ID="dsNT" EmtyRowPolicy="None" runat="server" />
	</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</table>
		<DS:NotesDataSource ID="ds" SelectTimeOut="120" OrderBys="NoteDate DESC" EmtyRowPolicy="OnlyIfEmpty" runat="server">
			<SelectParameters><asp:ControlParameter PropertyName="ApplID" Name="LoanID" DefaultValue="0" Type="Object" /></SelectParameters>
		</DS:NotesDataSource>
		<asp:Panel ID="pnlNote" style='display:none;' CssClass="NotePopup" runat="server"></asp:Panel>
		<ajaxtk:HoverMenuExtender BehaviorID="hvrNote" TargetControlID="pnlNote" PopupControlID="pnlNote" runat="server" />
<script>
	function InitNoteHover(element, html) {
		if (!element.initialized) {
			element.initialized = true;
			$addHandler(element, "mouseout", function() { clearTimeout(InitNoteHover.proc); });
		}
		if (event) {
			clearTimeout(InitNoteHover.proc);
			return InitNoteHover.proc = setTimeout(function() { InitNoteHover(element, html) }, 200);
		}
		clearTimeout(InitNoteHover.proc);
		var hover = $find("hvrNote");
		if ( hover && hover._element == element) return;
		if (hover) { hover.dispose(); hover = null; }
		$create(AjaxControlToolkit.HoverMenuBehavior, { "HoverCssClass": "NoteHover",
			"HoverDelay": 0,
			"OffsetX": 50,
			"dynamicServicePath": "/manager/USIX/USIXBridge.aspx",
			"id": "hvrNote",
			"popupElement": pnlNote()
		}, null, null, element);
		hover = $find("hvrNote");
		hover._popupElement.innerHTML = html;
		//hover._onmouseover();	hover._onHover();
		InitNoteHover.proc = setTimeout(function() { hover._onmouseover(); hover._onHover(); }, 100);
};

function dial(ext,pwd,notePhone,counter){
	WSA.Admin.Dial(ext,pwd,notePhone,cb,wsNoteError);
	function cb(result){
		if( !result )return;
		if( counter > 10 )return WSA.Admin.OnHook(ext,pwd,null,wsNoteError);
		if( result.toLowerCase() == "onhook" )
			return setTimeout(function(){dial(ext,pwd,notePhone,(counter||0)+1)},1000);
		alert("Unknown result code ["+result+"].");
	}
}
function fetchDateDue(statusID){
	WSA.Admin.FetchNoteDateDue(statusID,cb,wsNoteError);
	function cb(result){
		if( txtDateDue().changed )return;
		txtDateDue().value = result;
	}
}
function fetchNoteActionCodes(sel,noteTypeID){
	WSA.Admin.FetchNoteActionCodes(noteTypeID,cb,wsNoteError);
	function cb(result){
		fillSelect(getRSFromDS(result),sel,"ActionLabel","ActionCodeID");
	}
}
function fetchNoteResultCodes(sel,noteActionCodeID){
	WSA.Admin.FetchNoteResultCodes(noteActionCodeID,cb,wsNoteError);
	function cb(result){
		fillSelect(getRSFromDS(result),sel,"Status","StatusID");
		$get("selStatus").onchange();
	}
}

function wsNoteError(result){
	showSOAPAlert(result.get_message());
}
</script>
